package pos.data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.csvreader.CsvWriter;

import pos.domain.Order;
import pos.utils.UIDGenerator;

public class CSVOrderDAO implements IOrderDAO {
    
	private String outputFile = "data/order.csv";
    ICreditCardDAO cdao;
    IDetailDAO ddao;
    IAddressDAO adao;

    public CSVOrderDAO() {
        cdao = new CSVCreditCardDAO();
        ddao = new CSVDetailDAO();
        adao = new CSVAddressDAO();
    }
    
    private CsvWriter openFileWrite() {

		CsvWriter csvOutput = null;
		// before we open the file check to see if it already exists
		boolean alreadyExists = new File(outputFile).exists();

		try {
			// use FileWriter constructor that specifies open for appending
			csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

			// if the file didn't already exist then we need to write out the
			// header line
			if (!alreadyExists) {
				csvOutput.write("OID");
				csvOutput.write("orderID");
				csvOutput.write("addressOID");
				csvOutput.write("creditCardOID");
				csvOutput.write("timeplaced");
				csvOutput.write("placedbycustomer");
				csvOutput.endRecord();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return csvOutput;

	}

	private void closeFileWrite(CsvWriter writer) {
		writer.close();

	}


    public void delete(String OrderID) {
    	//TODO
    }


    public List selectAllOrders() {
        //TODO
    	return null;
    }

    public void insertOrder(Order o) {
        //insert credit card
        String oidc = UIDGenerator.getInstance().getKey();
        cdao.insert(oidc, o.getPayment());

        //insert address
        String oida = UIDGenerator.getInstance().getKey();
        adao.insert(oida, o.getDeliverto());

        //insert order
        String oido = UIDGenerator.getInstance().getKey();
       
        	
        	//write the order into the file
        	CsvWriter writer = openFileWrite();
        	try {
				writer.write(oido);
				writer.write(o.getOrderID());
				writer.write(oida);
				writer.write(oidc);
				writer.write(String.valueOf(o.getTimeplaced().getTime()));
				writer.write(o.getPlacedbyCustomer());
				writer.endRecord();
			} catch (IOException e) {
				e.printStackTrace();
			}

        	
        	//write the details using the DAO file
        	ddao.insert(o.getDetails(), oido);
        	closeFileWrite(writer);
      
    }

	@Override
	public Order selectOldOrder() {
		// TODO Auto-generated method stub
		return null;
	}
}

